package az.mecid.rssreader.server.services;

import az.mecid.rssreader.client.model.FeedItem;
import az.mecid.rssreader.client.services.FeedService;
import az.mecid.rssreader.model.entity.FeedItemEntity;
import az.mecid.rssreader.model.entity.SubscriptionEntity;
import az.mecid.rssreader.model.utils.EMF;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: mega
 * Date: 17.03.2010
 * Time: 19:43:48
 */
@SuppressWarnings("unchecked")
public class FeedServiceImpl extends RemoteServiceServlet implements FeedService {

    private Logger logger = Logger.getLogger(FeedServiceImpl.class.getName());

    public List<FeedItem> getFeedItems() {

        List<FeedItem> items = new ArrayList<FeedItem>();
        User user = UserServiceFactory.getUserService().getCurrentUser();

        EntityManager em  = EMF.get().createEntityManager();
        try {
            Query query = em.createQuery("select e from SubscriptionEntity e where e.user = :user");
            query.setParameter("user", user);

            List<SubscriptionEntity> subscriptions;
            EntityTransaction transaction = em.getTransaction();
            try {

                transaction.begin();
                subscriptions = query.getResultList();
                transaction.commit();

            } finally {
                if(transaction.isActive())
                    transaction.rollback();
            }

            List<FeedItemEntity> feedItemEntities = null;
            StringBuffer sql = queryCreator(subscriptions);

            if(sql != null){

                query = em.createQuery(sql.toString());
                query.setMaxResults(10);

                transaction = em.getTransaction();
                try{
                    transaction.begin();
                    feedItemEntities = query.getResultList();
                    transaction.commit();

                }finally {
                    if(transaction.isActive())
                        transaction.rollback();
                }

                for (FeedItemEntity entity : feedItemEntities) {
                    String title = entity.getTitle();
                    String url = entity.getUrl().getValue();
                    String description = entity.getDescription().getValue();

                    items.add(new FeedItem(title, description, url));
                }
            }
        }finally {
            em.close();
        }
        return items;
    }

    private StringBuffer queryCreator(List<SubscriptionEntity> subscriptions){

        if (!subscriptions.isEmpty()) {
            StringBuffer sql = new StringBuffer();
            sql.append("select e from FeedItemEntity e where ");

            int n = subscriptions.size();
            for(int i=0; i<n; ++i){
                if(i == n-1)
                    sql.append("e.feed_id = ").append(subscriptions.get(i).getFeed_id());
                else
                    sql.append("e.feed_id = ").append(subscriptions.get(i).getFeed_id()).append(" OR ");
            }
            sql.append(" ORDER BY e.time DESC");
            return sql;
        }
        return null;
    }
}